package Query.SearchEngine;
import Database.Document;
import java.util.Vector;
import Query.*;
import com.google.soap.search.*;

public class GoogleEngineAdapter implements IEngineAdapter {
    
    public GoogleEngineAdapter() { }    
    
    public Vector<Document> Query(String query, int length)
    {
        Vector<Document> result = new Vector<Document>();
        try
        {
            GoogleSearch googleSearch = new GoogleSearch();

            googleSearch.setKey(SearchEnginesKeys.GOOGLE_KEY);
            googleSearch.setQueryString(query);
            googleSearch.setMaxResults(length);

            GoogleSearchResult searchResult = googleSearch.doSearch();
            GoogleSearchResultElement[] results = searchResult.getResultElements();

            if (results.length == 0)
                return null;
            else
            {
                for (int index = 0; index < results.length; index++)
                {
                    //Title
                    String title = results[index].getTitle();
                    title = title.replaceAll("<.*?>", "");     

                    //URL
                    String url = results[index].getURL();
                 
                    //Summary
                    String summary = results[index].getSnippet();
                    summary = summary.replaceAll("<.*?>", "");
                    result.add(new Document(url.trim(), title, summary, this.getSearchEngine()));
                }
            }
            return result;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
    
    public SearchEnginesTypes getSearchEngine()
    {
        return SearchEnginesTypes.GOOGLE;
    }
}
